package com.example.donghuihui.androidframe.utils.aes;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密工具类
 */
public class AESUtil {
    public static String TAG = "AESUtil";
    static final String KEY_ALGORITHM = "AES";
    static final String CIPHER_ALGORITHM_ECB = "AES/ECB/PKCS5Padding";
    static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding";
    static final String CIPHER_ALGORITHM_CBC_CS7 = "AES/CBC/PKCS7Padding";
    static final String CIPHER_ALGORITHM_CBC_NoPadding = "AES/CBC/NoPadding";
    private static final String AESIV = "0102030102030102";
    private static final String IV_KEY = "aes key";//密钥

    /**
     * 加密
     *
     * @param content 要加密的内容
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String kkey) {
        try {
            String key = MD5Utils.getMd5Value(kkey);
            SecretKeySpec skeySpec = new SecretKeySpec(key.substring(0, 16).getBytes(), "AES");
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC_CS7);
            IvParameterSpec iv = new IvParameterSpec(key.substring(16, 32).getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(content.getBytes());
            return Base64.encodeToString(encrypted, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String decrypt(String content, String kkey) {
        try {
            String key = MD5Utils.getMd5Value(kkey);
            SecretKeySpec skeySpec = new SecretKeySpec(key.substring(0, 16).getBytes(), "AES");
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC_CS7);
            IvParameterSpec iv = new IvParameterSpec(key.substring(16, 32).getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.decode(content, Base64.DEFAULT);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密
     */
    public static String encode(String content) {

        return encrypt(content, IV_KEY);
    }

    /**
     * 解密
     */
    public static String decode(String content) {

        return decrypt(content, IV_KEY);
    }
}
